//
//  MyTermBondsViewController.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/4/21.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "MyTermBondsViewController.h"
#import "MyTermBonudsCell.h"
#import "EmptyTableViewCell.h"
#import "HistoryBonudsViewController.h"
#import "MyTermBonudsModel.h"

@interface MyTermBondsViewController ()<UITableViewDelegate,UITableViewDataSource,HTTPClientDelegate>
{
    NSMutableArray *_dataArray;
}

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) NSInteger     currPage;
@property (nonatomic, assign) NSInteger     totalCount;

@end

@implementation MyTermBondsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self resetNavigationBar];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.view.backgroundColor = KbackgroundColor;
    
    
    [self initData];
    [self initView];
    
}

#pragma mark - 历史定期
- (void)rightBarButtonClick {
    //历史定期
    HistoryBonudsViewController *historyBonus = [[HistoryBonudsViewController alloc] init];
    [self.navigationController pushViewController:historyBonus animated:YES];
}

#pragma mark - 再存一笔
- (IBAction)tenderButtonClick:(UIButton *)sender {
    
    [self.tabBarController setSelectedIndex:1];

    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [CommonClass completion:^(bool finish) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateEasyFinance" object:self];
        
    } afterDelay:0.5];
 
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    
}

- (void)initView {
    
    
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.estimatedRowHeight = KAdaptNum(105);
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
     _tableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //    [self.tableView headerBeginRefreshing];
     [_tableView.mj_header beginRefreshing];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
     _tableView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
   
}

#pragma mark - 请求数据
- (void)initData {
    _dataArray = [NSMutableArray array];

}

- (void)requestData {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"512" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:[NSString stringWithFormat:@"%ld",(long)_currPage] forKey:@"currPage"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters withViewController:self];
}


#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    [self hiddenRefreshView];
    NSDictionary *dics = obj;
    DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        
        if (_currPage == 1) {
            [_dataArray removeAllObjects];
        }
        NSArray *list = dics[@"list"];
        if (list.count) {
            for (NSDictionary *subDict in list) {
                MyTermBonudsModel *model = [MyTermBonudsModel mj_objectWithKeyValues:subDict];
                
                model.termBonusId = [NSString stringWithFormat:@"%@",subDict[@"id"]];
                model.investTime = [NSString converDate:[[subDict objectForKey:@"start_time"] objectForKey:@"time"] withFormat:@"yyyy-MM-dd HH:mm:ss"];
                if ([subDict objectForKey:@"end_time"] && ![[subDict objectForKey:@"end_time"] isKindOfClass:[NSNull class]]) {
                    model.lastRepayTime = [NSString converDate:[[subDict objectForKey:@"end_time"] objectForKey:@"time"] withFormat:@"yyyy-MM-dd"];
                }
                switch (model.period) {
                    case 3:
                    {
                        model.investmentType = 1;
                        model.title = @"季季增";
                    }
                        break;
                    case 6:
                    {
                        model.investmentType = 2;
                        model.title = @"半年赢";
                    }
                        break;
                        
                    case 12:
                    {
                        model.investmentType = 3;
                        model.title = @"年年丰";
                    }
                        break;
                        
                        
                    default:
                        model.investmentType = 1;
                        model.title = @"季季增";
                        break;
                }

                [_dataArray addObject:model];
            }
        }
        [_tableView reloadData];
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [self hiddenRefreshView];
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    _isLoading = NO;
    [self hiddenRefreshView];
}

#pragma mark - 重新加载
- (void)reloadRequest
{
    [self headerRereshing];
}

#pragma mark - 刷新
- (void)headerRereshing {
    _currPage = 1;
    [self requestData];
}

- (void)footerRereshing {
    _currPage ++;
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}
#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_dataArray.count) {
//        MyTermBonudsModel *model = _dataArray[indexPath.section];
//        
//        TermBonusDetailViewController *termBonusDetailVC = [[TermBonusDetailViewController alloc] init];
//        termBonusDetailVC.bidID = [NSString stringWithFormat:@"%ld",(long)model.bidId];
//        termBonusDetailVC.investId = model.termBonusId;
//        termBonusDetailVC.status = model.status;
//        [self.navigationController pushViewController:termBonusDetailVC animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count>0?_dataArray.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count) {
        static NSString *cellID = @"cellID";
        MyTermBonudsCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"MyTermBonudsCell" owner:self options:nil][0];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        }
        cell.detailBackView.hidden = NO;
        [cell refreshCellWithModel:_dataArray[indexPath.section]];
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(105));
        return cell;
    }else {
        EmptyTableViewCell *cell = [[EmptyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = KbackgroundColor;
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, _tableView.frame.size.height);
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10.0f;
    }
    return 5.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.0f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
